package com.hospital.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hospital.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@CrossOrigin(origins = "*",maxAge = 3600)
public class FlaskController {
    @PostMapping("flask")
    public R predict() {
        try {
            // 构建请求数据
            JSONObject jsonData = new JSONObject();
            jsonData.put("steps", 6);  // 预测未来 5 个时间点

            // 创建 URL 对象
            URL url = new URL("http://127.0.0.1:5000/predict_arima");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和请求头
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonData.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            int status = connection.getResponseCode();
            InputStream is = (status >= 200 && status < 300) ? connection.getInputStream() : connection.getErrorStream();

//            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
//            StringBuilder response = new StringBuilder();
//            String responseLine;
            StringBuilder response = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            }

//            while ((responseLine = br.readLine()) != null) {
//                response.append(responseLine.trim());
//            }

            // 处理响应
//            if (status == 200) {
//                ObjectMapper objectMapper = new ObjectMapper();
//                JsonNode rootNode = objectMapper.readTree(response.toString());
//                System.out.println("Predictions: " + rootNode.get("predictions"));
//                return R.ok("预测成功").put("data", rootNode.get("predictions"));
//            } else {
//                System.out.println("Request failed with status code: " + status);
//                System.out.println("Response: " + response);
//                return R.error();
//            }
            if (status == 200) {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(response.toString());

                // 获取所有需要的字段
                JsonNode historicalDataNode = rootNode.get("historical_data");
                JsonNode predictionsNode = rootNode.get("predictions");

                // 检查字段是否存在
                if (historicalDataNode != null && historicalDataNode.isArray() &&
                        predictionsNode != null && predictionsNode.isArray()) {

                    // 返回包含所有数据的响应
                    return R.ok("预测成功")
                            .put("historical_data", historicalDataNode)
                            .put("predictions", predictionsNode);
                } else {
                    return R.error("预测结果格式错误");
                }
            } else {
                // 处理错误响应
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode errorNode = objectMapper.readTree(response.toString());
                String errorMessage = errorNode.has("error") ? errorNode.get("error").asText() : "未知错误";
                return R.error("请求失败: " + errorMessage);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}
